/*******************************************************************************
 * Copyright (c) 2006 CEA List.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CEA List - initial API and implementation
 *******************************************************************************/
package com.cea.papyrus.core.ui.wizards;


import java.util.Iterator;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.dialogs.ResourceSelectionDialog;
import org.eclipse.ui.ide.IDE;
import org.eclipse.uml2.uml.resource.UMLResource;

import com.cea.papyrus.core.IPapyrusUIConstants;
import com.cea.papyrus.core.utils.Debug;
import com.cea.papyrus.core.utils.DiResourceSet;



/**
 * Create new new .uml2-file.
 */
public class CreateModelFromFileWizard extends Wizard implements INewWizard {

	/**
	 * 
	 */
	public static final String WIZARD_ID = IPapyrusUIConstants.WIZARD_ID+".createmodelfromfile";
	
	/**
	 * 
	 */
	private SelectUmlFilePage page1;
	
	/**
	 * 
	 */
	private int debugChannel=1;

	/* (non-Javadoc)
	 * @see org.eclipse.jface.wizard.IWizard#addPages()
	 */
	/**
	 * 
	 */
	@Override
	public void addPages() {
		// add pages to this wizard
		Debug.debug(this," Calls PapyrusCreationWizard.addPage", debugChannel);

		addPage(page1); 
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection)
	 */
	/**
	 * 
	 * 
	 * @param workbench 
	 * @param selection 
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		// create pages for this wizard
		Debug.debug(this," Calls PapyrusCreationWizard.init", debugChannel);
		
		page1 = new SelectUmlFilePage(workbench);//workbench, selection); 
		page1.init(selection);


	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.wizard.IWizard#performFinish()
	 */
	/**
	 * 
	 * 
	 * @return 
	 */
	@Override
	public boolean performFinish() {
		Debug.debug(this," Calls PapyrusCreationWizard.performFinish", debugChannel);
		return page1.finish();

	}

	/**
	 * This WizardPage can create an empty .uml2 file for the PapyrusEditor.
	 */
	private class SelectUmlFilePage extends WizardPage {
		
		/**
		 * 
		 */
		private Text sourceFileField;
		
		/**
		 * 
		 */
		private IFile umlFile;
		
		/**
		 * 
		 */
		private IPath initialSourcePath;
		
		/**
		 * 
		 */
		private final IWorkbench workbench;

		/**
		 * 
		 * 
		 * @param workbench 
		 */
		public SelectUmlFilePage(IWorkbench workbench){
			super("SelectUMLFile");
			setTitle("UML file Wizard");
			setDescription("Create model from an existing UML file");
			this.workbench = workbench;
		}
		
		/**
		 * 
		 * 
		 * @param parent 
		 */
		public void createControl(Composite parent){
			Composite container= new Composite(parent, SWT.NULL);
			final Shell theShell= parent.getShell();
			final GridLayout gridLayout= new GridLayout();
			gridLayout.numColumns=3;
			container.setLayout(gridLayout);
			setControl(container);

			final Label label =new Label(container,SWT.NONE);
			final GridData gridData= new GridData();
			gridData.horizontalSpan=3;
			label.setLayoutData(gridData);
			label.setText("Select the UML file from which diagram "+
			"will be generated");
			final Label label_1= new Label(container, SWT.NONE);
			final GridData gridData_1= new GridData();
			label_1.setLayoutData(gridData_1);
			label_1.setText("UML file: ");

			sourceFileField= new Text(container, SWT.BORDER);
			sourceFileField.addModifyListener(new ModifyListener(){
				public void modifyText(ModifyEvent e){
					updatePageComplete();
				}
			});
			sourceFileField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
			final Button buttonBrowse= new Button(container, SWT.NONE);
			buttonBrowse.addSelectionListener(new SelectionListener(){
				public void widgetDefaultSelected(SelectionEvent e){
					//browseForSourceFile();
				}
				public void widgetSelected(SelectionEvent e){
					ResourceSelectionDialog dialog =
						new ResourceSelectionDialog(getShell(), ResourcesPlugin.getWorkspace().getRoot(), "test");
					dialog.open();
					if ((dialog.getResult()).length>1){
						setErrorMessage("You have to choose only one File");

					}
					initialSourcePath= ((IFile)dialog.getResult()[0]).getLocation();
					IPath path =initialSourcePath;
					IPath rootLoc= ResourcesPlugin.getWorkspace().getRoot().getLocation();
					if (rootLoc.isPrefixOf(path)) {
						path =path.setDevice(null).removeFirstSegments(rootLoc.segmentCount());
					}
					umlFile=((IFile)dialog.getResult()[0]);
					sourceFileField.setText(path.toString());
					updatePageComplete();

				}
			});
			buttonBrowse.setText("Browse...");
			initContents();
		}

		/**
		 * 
		 * 
		 * @param selection 
		 */
		public void init(ISelection selection){
			if (!(selection instanceof IStructuredSelection)) {
				return;
			}

			Iterator iter= ((IStructuredSelection)selection).iterator();

			while (iter.hasNext()){
				Object item = iter.next();

				if (item instanceof IFile){
					IFile file= (IFile)item;
					if (file.getName().endsWith("."+UMLResource.FILE_EXTENSION)){
						initialSourcePath=file.getLocation();
						umlFile=file;
					}
				}
			}
		}
		
		/**
		 * 
		 */
		private void initContents(){
			if (initialSourcePath!=null){
				IPath rootLoc=ResourcesPlugin.getWorkspace().getRoot().getLocation();
				IPath path =initialSourcePath;
				if (rootLoc.isPrefixOf(path)) {
					path =path.setDevice(null).removeFirstSegments(rootLoc.segmentCount());
				}
				sourceFileField.setText(path.toString());
				updatePageComplete();
				setErrorMessage(null);
				setMessage(null);
			}
		}

		/**
		 * 
		 * 
		 * @return 
		 */
		public IPath getSourceLocation(){
			return initialSourcePath;
		}
		
		/**
		 * 
		 */
		private void updatePageComplete(){
			setPageComplete(false);
			
			IPath sourceLoc= getSourceLocation();
			if ((sourceLoc==null)||!sourceLoc.toFile().exists()){
				setMessage(null);
				setErrorMessage("Please select an existing UML file");
				setPageComplete(false);
			}
			else{
				
				setPageComplete(true);
			}
		}

		/**
		 * 
		 * 
		 * @return 
		 */
		public boolean finish(){
			if (umlFile!=null){
			DiResourceSet resources = new DiResourceSet(null);
			resources.createDi2Resources(umlFile);
			IWorkbenchPage page = workbench.getActiveWorkbenchWindow().getActivePage();

			
			try {
				IPath di2Path = umlFile.getLocation().removeFileExtension();
				di2Path=di2Path.addFileExtension("di2");
				IFile di2File=ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(di2Path);
				IDE.openEditor(page, di2File, true);
			} catch (PartInitException e) {
				e.printStackTrace();
				return false;
			}
			return true;}
			else{
				return false;}
			}
	}

}
